﻿
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Threading.Tasks;

using FreeSql;
using Kalman;
using Newtonsoft.Json.Linq;
using Kalman.Extensions;

namespace QuDao
{
    /// <summary>
    /// 数据表cms_video关联的业务对象，处理该表相关的业务逻辑
    /// </summary>
    public sealed partial class VideoBO : SingletonBase<VideoBO>
    {
        readonly IFreeSql fsql;
        public VideoBO() : base()
        {
            fsql = ServiceLocator.Instance.GetRequiredService<IFreeSql>();
        }

        /// <summary>
        /// 获取商品视频
        /// </summary>
        /// <param name="id">主键ID的值</param>
        /// <returns></returns>
        public T GetItem<T>(int id)
        {
            if (id <= 0) return default;
            var item = fsql.Select<Video>().Where(a => a.VideoID == id).ToOne<T>();
            return item;
        }

        public Video GetItem(int id)
        {
            return GetItem<Video>(id);
        }

        /// <summary>
        /// 获取视频详情
        /// </summary>
        /// <param name="id">视频ID</param>
        /// <returns></returns>
        public VideoDetailsDto GetDetails(int id)
        {
            var dto = GetItem<VideoDetailsDto>(id);
            return dto;
        }

        /// <summary>
        /// 获取商品视频列表
        /// </summary>
        /// <param name="goodsID">商品ID</param>
        /// <returns></returns>
        public List<VideoDto> GetListByGoods(int goodsID)
        {
            var list = fsql.Select<Video>()
                .Where(a => a.GoodsID == goodsID)
                .OrderByDescending(a => a.SortFlag)
                .OrderByDescending(a => a.VideoID)
                .ToList<VideoDto>();
            return list;
        }

        /// <summary>
        /// 获取视频数据列表
        /// </summary>
        /// <returns></returns>
        public List<T> GetList<T>(int[] ids)
        {
            if (ids == null || ids.Length == 0) return new List<T>();
            var list = fsql.Select<Video>().Where(a => ids.Contains(a.VideoID)).ToList<T>();
            return list;
        }

        /// <summary>
        /// 新增视频
        /// </summary>
        public long Add(VideoAddDto dto)
        {
            var gooods = GoodsBO.Instance.GetItem(dto.GoodsID) ?? throw new AppException($"关联商品不存在：{dto.GoodsID}");

            var entity = dto.CopyTo<Video>();

            entity.TID = gooods.TID;
            entity.CreateTime = DateTime.Now;
            entity.ModifyTime = DateTime.Now;
            entity.VideoID = (int)fsql.Insert(entity).ExecuteIdentity();
            return entity.VideoID;
        }

        /// <summary>
        /// 修改视频
        /// </summary>
        public int Modify(VideoModifyDto dto)
        {
            var item = GetItem<Video>(dto.VideoID) ?? throw new AppException($"视频不存在：{dto.VideoID}");

            var update = fsql.Update<Video>(dto.VideoID).Set(a => a.ModifyTime, DateTime.Now);

            if (!string.IsNullOrEmpty(dto.CoverUrl) && dto.CoverUrl != item.CoverUrl) update.Set(a => a.CoverUrl, dto.CoverUrl);
            if (dto.SortFlag != item.SortFlag) update.Set(a => a.SortFlag, dto.SortFlag);
            if (dto.Memo != item.Memo) update.Set(a => a.Memo, dto.Memo);

            if (!dto.VideoUrl.IsNullOrEmpty() && dto.VideoUrl != item.VideoUrl)
            {
                update.Set(a => a.VideoUrl, dto.VideoUrl).Set(a => a.FileSize, dto.FileSize);
            }

            return update.ExecuteAffrows();
        }

        /// <summary>
        /// 删除视频数据
        /// </summary>
        /// <returns>返回影响行数</returns>
        public int Delete(int[] ids)
        {
            if (ids == null || ids.Length == 0) return 0;
            return fsql.Delete<Video>().Where(a => ids.Contains(a.VideoID)).ExecuteAffrows();
        }

        /// <summary>
        /// 删除视频数据
        /// </summary>
        /// <returns>返回影响行数</returns>
        public int Delete(int id)
        {
            return fsql.Delete<Video>(id).ExecuteAffrows();
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="req">分页查询请求对象</param>
        public PagingResult<T> Query<T>(PagingRequest req, int tid, int goodsID)
        {
            if (req == null) throw new AppException("查询数据不能为空");

            var select = fsql.Select<Video>()
                .Where(a => a.TID == tid)
                .WhereIf(goodsID > 0, a => a.GoodsID == goodsID); ;
            foreach (var item in req.FilterItems)
            {
                switch (item.Field)
                {
                    //case "VideoID":
                    //    select.Where(a => a.VideoID == int.Parse(item.Value));
                    //    break;
                    case "Memo":
                        select.Where(a => a.Memo.Contains(item.Value));
                        break;
                    default:
                        break;
                }
            }

            if (!string.IsNullOrEmpty(req.SortExp))
            {
                select.OrderBy(req.SortExp);//自定义排序
            }
            else
            {
                select.OrderByDescending(a => a.SortFlag);
                select.OrderByDescending(a => a.VideoID);//默认排序
            }

            var sql = select.ToSql();

            var list = select.Count(out var total).Page(req.PageIndex, req.PageSize).ToList<T>();
            return new PagingResult<T>
            {
                PageIndex = req.PageIndex,
                PageSize = req.PageSize,
                Data = list,
                Total = (int)total
            };
        }

        public PagingResult<Video> Query(PagingRequest req, int tid, int goodsID)
        {
            return Query<Video>(req, tid, goodsID);
        }
    }
}
